package com.threeonemeeting.task;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.snda.lib.http.HttpUtil;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.db.AppDBHelper;
import com.threeonemeeting.model.FullMeetingInfo;

public class ProtocolHelper {

	public static void setErr(int nError, Map<String, Object> mapData) {
		if (mapData == null)
			return;

		mapData.put(HttpUtil.KEY_ERROR_CODE, nError);
		String errmsg = HttpUtil.getErrorDesc(nError);
		mapData.put(HttpUtil.KEY_ERROR_MSG, errmsg);
	}

	public static void getFaildResponse(Map<String, Object> mapData,
			JSONObject jsonResp) {

		String strFailed = "";

		try {
			strFailed = jsonResp.getString("failure");
			if (strFailed == null) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return;
			}

			if (strFailed.equalsIgnoreCase("true") == false) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return;
			}

			JSONObject dataJson = jsonResp.getJSONObject("data");
			if (dataJson == null) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return;
			}

			String strErrorMsg = dataJson.getString("error");
			setErr(Const.AppError.ERROR_ENROLL, mapData);
			mapData.put("errmsg", strErrorMsg);
			return;

		} catch (JSONException e) {
			setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
			return;
		}
	}
	
	/**
	 * @desc 解析会议报文
	 * @param jData
	 * @return
	 */
	public static FullMeetingInfo getFullMeetingInfo(JSONObject jData) {
		try {
			FullMeetingInfo fullInfo = new FullMeetingInfo();

			fullInfo.nId = jData.getInt("Id");
			fullInfo.strTitle = jData.getString("Title");
			fullInfo.strLogoUrl = jData.getString("Logo");
			fullInfo.lPrice = jData.getInt("Price");
			fullInfo.strBeingTime = jData.getString("DateFrom");
			if (fullInfo.strBeingTime != null) {
				fullInfo.strBeingTime = fullInfo.strBeingTime.replace('T', ' ');
			}
			fullInfo.strEndTime = jData.getString("DateTo");
			if (fullInfo.strEndTime != null) {
				fullInfo.strEndTime = fullInfo.strEndTime.replace('T', ' ');
			}

			fullInfo.strAddress = jData.getString("Address");
			fullInfo.strSummary = jData.getString("Summary");
			fullInfo.strJoinLimitTime = jData.getString("JoinLimitTime");
			if (fullInfo.strJoinLimitTime != null) {
				fullInfo.strJoinLimitTime = fullInfo.strJoinLimitTime.replace(
						'T', ' ');
			}

			fullInfo.fLatitude = jData.getLong("Latitude");
			fullInfo.fLongitude = jData.getLong("Longitude");
			fullInfo.strEventTypeName = jData.getString("EventTypeName");
			
			AppDBHelper db = DataCenter.getInstance().getDB();
			db.addMeeting(fullInfo);

			return fullInfo;
		} catch (JSONException ex) {
			Log.e(Const.Tag, "Parser Meeting Error: " + ex.getMessage());
		}
		
		return null;
	}
}
